import Dialog from "./src";

export default {
	install(Vue) {
		
		const Controller = Vue.extend(Dialog);
		let instance = null;
		let executor = null;

		// 添加回调函数
		Controller.prototype.callback = data => {
			if (typeof data !== "undefined") {
				executor.resolve(data);
			} else {
				executor.reject();
			}
		};

		// 公用弹出组件
		function dialogFun(...args) {
			// 按需挂载实例
			if (!instance) {
				instance = new Controller().$mount();
				document.body.appendChild(instance.$el);
			}

			// 显示
			instance.display(...args);

			if (args[0] !== "loading") {
				return new Promise((resolve, reject) => {
					executor = {resolve, reject};
				});
			}
		}

		// 挂载实例
		Vue.prototype.$alert = dialogFun.bind(null, "alert");
		Vue.prototype.$prompt = dialogFun.bind(null, "prompt");
		Vue.prototype.$confirm = dialogFun.bind(null, "confirm");
		Vue.prototype.$diaPreloader = {
			show: dialogFun.bind(null, "loading"),
			hide() {
				instance && instance.hide();
			}
		}
	}
};